<template>
  <div class="home container" id="fullscreen-container" ref="fullscreen">
    <slot name="search"></slot>
    <div class="controlbox">
      <el-tooltip class="item" effect="dark" content="请选择一个区域，进行拆分" placement="left-start">
        <i class="el-icon-split" style="color:blue; margin-top: 10px;" @click="drawnewLine"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="请选择一个区域，进行挖洞" placement="left-start">
        <i class="el-icon-burrow" style="color:blue; margin-top: 10px;" @click="drawBurrow(true)"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="请选择一个区域，进行挖洞" placement="left-start">
        <i class="el-icon-burrow" style="color:blue; margin-top: 10px;" @click="drawBurrow(false)"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="按住回车选择多个区域，不相邻进行合并" placement="left-start">
        <i class="el-icon-join" style="color:blue; margin-top: 10px;" @click="joinHandler"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="按住回车选择多个区域，相邻进行合并" placement="left-start">
        <i class="el-icon-union" style="color:blue; margin-top: 10px;" @click="unionHandler"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="开始修改图层" placement="left-start">
        <i class="el-icon-edit" style="color:blue;margin-top: 10px;" @click="startModify('json')"></i>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="停止修改" placement="left-start">
        <i class="el-icon-video-pause" style="color:yellowgreen;margin-top: 10px;" @click="clearModify"></i>
      </el-tooltip>
      
    </div>
    <div id="map" class="map-container" :style="{'width':mapWidth,'height':mapHeight}"></div>
      <el-tooltip class="item" ref="elTooltip"   :append-to-body="false"   effect="light" placement="left">
      <div slot="content">
        <div class="mapbox">
          <li @click="mapChangeHandler(0)" :class="models.active[0]?'activeStyle':''">
            <img src="../assets/image/dixing.jpg" width="100px" height="50px">
            <div class="on">地形地图</div>
          </li>
          <li @click="mapChangeHandler(1)" :class="models.active[1]?'activeStyle':''">
            <img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
            <div class="on">影像地图</div>
          </li>
          <li @click="mapChangeHandler(2)" :class="models.active[2]?'activeStyle':''">
            <img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
            <div class="on">离线影像</div>
          </li>
        </div>
      </div>
      <div class="map0"></div>
    </el-tooltip>

  </div>
</template>
<script lang="ts">
import {Feature} from "ol";
import { MultiPolygon } from 'ol/geom';
import { Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import { Component, Vue,Prop,Watch,Ref,Emit} from 'vue-property-decorator';
import Draw from 'ol/interaction/Draw';
import Select from 'ol/interaction/Select';
import {createStyle,createMap,outputJson,mapChangeType,loadGeoJson,
  drawLineCut,joinFeatures,unionFeatures,unionCoordinates,getPointFeature,
  createLayer,
  
} from '@/utils/map'
import Modify from 'ol/interaction/Modify'
import { click,platformModifierKeyOnly } from "ol/events/condition";

@Component({
  components: {}
})
export default class CountyMap extends Vue {

@Prop() private mapWidth!: string;
@Prop() private mapHeight!: string;
@Prop() private vectorId!: string;
@Prop() private position!:any;

@Ref('fullscreen') private fullscreen!:any;
@Ref('elTooltip') private elTooltip!:any;

models: any = {
 
  tempSource: null,
  map: null,
  geoJsonSource: null,
  polygonSource: new VectorSource({
    wrapX: false 
  }),
  lineSource:new VectorSource({
    wrapX: false 
  }),
  polygonLayer:null,
  drawGeoJson: '',
  active: [true, false,false],
  modify: null,
  selectFeature:[],
  select:null,
  places:[],
}


initMap() {
  this.models.map = createMap([111.670801, 40.818311]);
  this.fullscreen.appendChild(this.elTooltip.popperVM.$el)
  let vector = new VectorLayer({
      source: this.models.lineSource,
      style: createStyle('red','red','green'),
  });
  this.models.map.addLayer(vector);


  const slt = new Select({ condition: click, toggleCondition: platformModifierKeyOnly,multi:true});
  this.models.map.addInteraction(slt)
  this.models.select = slt;
  slt.on("select", (evt) => {
      this.models.selectFeature = evt.selected;
   
      for(let i=0; i< this.models.selectFeature.length;i++){
        const geometry=  this.models.selectFeature[i].getGeometry();
        const type =geometry.getType();
        console.log(type)
        console.log(geometry)
        switch(type){
          case 'Polygon':
         
            console.log(geometry.getCoordinates())
            break;
            case 'MultiPolygon':
            console.log(geometry.getCoordinates())
              break;
              case 'Point':
                break;
        }
      }
   
  });
}

mapChangeHandler(x){
  mapChangeType(this.models.map.getLayers(),x,this.models.active);
}

startModify(type: any) {
  switch (type) {
    case 'json':
      this.models.modify = new Modify({
        source: this.models.geoJsonSource,
      });
      break;
  }
  this.models.map.addInteraction(this.models.modify);
}

relationArea(){
  this.clearModify();
  if(!this.models.selectFeature || this.models.selectFeature.length != 1){

    this.$message.info("请先选择一个地图区域，进行关联");
    return;
  }
  outputJson(this.models.selectFeature).then(res =>{
    this.models.drawGeoJson = res.data.id;
  });

}

saveModify() {
  this.clearModify();
  outputJson(this.models.geoJsonSource.getFeatures()).then(res =>{
    this.$message.success("区划图层已保存");
    this.models.drawGeoJson = res.data.id;
  }).catch(e =>{
    this.$message.error("区划图层保存失败");
    this.models.drawGeoJson = null;
  });
}

getGeoFile(){
  return  this.models.drawGeoJson;
}

@Watch('vectorId')
updateVectore(val: any) {
 
  if (this.models.geoJsonSource) {
     this.models.geoJsonSource.clear();
  }
  if (val) {
    this.models.geoJsonSource = loadGeoJson(val,this.models.map);
    this.$message.success("区划图层已刷新");
    if(!this.models.polygonLayer){
    this.models.polygonLayer = createLayer(this.models.polygonSource,createStyle("orange","darkgreen","red"));
    this.models.map.addLayer(this.models.polygonLayer);
    this.polygonLoaded();

  }
  }
}

joinHandler() {
  this.clearModify();
  const oldFeatures = this.models.select.getFeatures().array_;
  if (!oldFeatures|| oldFeatures.length < 2) {
    this.$message.info("请选择多个区域，再点击合并");
    return;
  }
  joinFeatures(oldFeatures,this.models.geoJsonSource);
  this.$message.success("区划图层合并完成");
}

unionHandler(){
  this.clearModify();
  const oldFeatures = this.models.select.getFeatures().array_;
  if (!oldFeatures || oldFeatures.length < 2 ) {
    const coords = oldFeatures[0].getGeometry().getCoordinates();
    if(coords.length >= 2){
      unionCoordinates(oldFeatures[0],this.models.geoJsonSource);
    }else{
      this.$message.info("请选择多个区域，再点击合并");
    }
 
    return;
  }
  unionFeatures(oldFeatures,this.models.geoJsonSource);
  this.$message.success("区划图层合并完成");
}


drawBurrow(freehand) {
  if(!this.models.selectFeature || this.models.selectFeature.length != 1){
    this.$message.info("请选择一个区域，再点击挖洞");
    return;
  }

  this.models.modify = new Draw({
      source: this.models.lineSource,
      type: 'Polygon',
      freehand:freehand,
      //Draw执行时采用的样式
      style: createStyle('red','green')
    
  });
  this.models.map.addInteraction(this.models.modify)
  const oldFeature = this.models.selectFeature[0];
  let oldCoord:any = null;
  const geometryType = oldFeature.getGeometry().getType();
  if(geometryType === 'Polygon'){
    oldCoord = oldFeature.getGeometry().getCoordinates()
  }else if(geometryType === 'MultiPolygon'){
    oldCoord = oldFeature.getGeometry().getCoordinates()[0];
  }
  this.models.modify.on("drawend", (evt) => {
    let coorArr = evt.feature.getGeometry().getCoordinates();
    let  coord:any=[];
    coord.push(oldCoord);
    coord[0].push(coorArr[0])
    this.models.map.removeInteraction(this.models.modify);
    
    let feature1 = new Feature({
        geometry: new MultiPolygon(coord),
    });
    this.models.geoJsonSource.removeFeature(oldFeature);
    this.models.geoJsonSource.addFeature(feature1);
  
    console.log(this.models.geoJsonSource.getFeatures()[0].getGeometry().getCoordinates());
    this.models.modify = null;
    this.$message.success("区划图层已完成挖洞");

  });
}

clearModify(){
  if(this.models.modify){
    this.models.map.removeInteraction(this.models.modify)
    this.models.modify = null;
    this.$message.success("已清理图层");
  }
  this.models.lineSource.clear();
}

clearVector(){
  if(this.models.geoJsonSource ){
    this.models.geoJsonSource.clear();
  }
 
}

drawnewLine() {

   const oldFeatures = this.models.select.getFeatures().array_;
    if (!oldFeatures|| oldFeatures.length == 0) {
      this.$message.info("请选择一个地图区域然后拆分");
      return;
    }
    console.log(oldFeatures)
    this.clearModify();
    this.models.lineSource.clear();
    this.models.modify = new Draw({
      source: this.models.lineSource,
      type: 'LineString',
      freehand:true,
      //Draw执行时采用的样式
      style: createStyle('red','red,','green')
    })

  
    this.models.map.addInteraction(this.models.modify)
    
    this.models.modify.on("drawend", (evt) => {
      let coorArr = evt.feature.getGeometry().getCoordinates();
      for (let f = 0; f < oldFeatures.length; f++) {
        const oldfeature = oldFeatures[f];
        const geometryType = oldfeature.getGeometry().getType();
        let oldfeaturecoordinates:any = null;
        if(geometryType === 'Polygon'){
          oldfeaturecoordinates= oldfeature.getGeometry().getCoordinates();
          drawLineCut(oldfeaturecoordinates,oldfeature,coorArr,this.models.geoJsonSource);
          this.$message.success("单图层拆分完成");
        }else if(geometryType === 'MultiPolygon'){
          const allCoords = oldfeature.getGeometry().getCoordinates();
          allCoords.forEach(coord =>{
            drawLineCut(coord,oldfeature,coorArr,this.models.geoJsonSource);
          })
          this.$message.success("多图层拆分完成");
        }
      }
      this.models.map.removeInteraction(this.models.modify);
      this.models.modify= null;
      this.models.selectFeature = null;
      this.models.lineSource.clear();
    });
    
}

setMarker(point:any) {

  let source = this.models.polygonLayer.getSource();
  //source.clear();
  source.addFeature(getPointFeature(point,'#3399CC','#fff'));
  
}

@Watch('position')
updatePosition(val:any){
  if(val){
        this.models.map.getView().animate({
        center: val, // 新的中心坐标
        zoom: 16,        // 新的缩放级别
        duration: 3000   // 动画持续时间（毫秒）
    });
    //this.setMarker(val);
  }
}

buildBaiduPalce(places,placeCard){
   placeCard.cityPoint(places,this.models.polygonLayer.getSource());
}

@Emit('polygonLoaded')
  polygonLoaded(){
    console.log('围栏已初始化完成');
  }

mounted() {
  this.initMap();
}
}
</script>
<style>
.map0 {
  opacity:0.8;
  width: 24px;
  height: 24px;
  background: url(../assets/image/tooltip.png) center center no-repeat;
  background-size: 16px 16px;
  position: absolute;
  right: 60px;
  top: 10px;
  z-index: 200;
  cursor: pointer;
}
.map1 {
  opacity:0.5;
  width: 250px;
  height: 40px;
  background: #000 center center no-repeat;
  position: absolute;
  right: 0px;
  top: 0px;
  z-index: 200;
  cursor: pointer;
}

.mapbox {
  width: 320px;
  height: 60px;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
}

.mapbox li {
  width: 100px;
  height: 50px;
  margin: 5px 0;
  display: block;
  position: relative;
  cursor: pointer;
}


.mapbox li .on {
  height: 16px;
  width: 100px;
  background-color: rgba(0, 0, 0, 0.3);
  color: #fff;
  font-size: 12px;
  position: absolute;
  bottom: 0;
  left: 0;
  display: none;
  text-align: center;
}
.mapbox li:hover .on{ display: block;}
.activeStyle {
  width: 100px;
  height: 50px;
  border: 1px solid #f00;
}
.container {
  border: 1px solid #42B983;
  position: relative;
  min-width: 100vh;
}

.controlbox {
  opacity:0.8;
  position: absolute;
  z-index: 10000;
  bottom: 200px;
  width: 18px;
  padding: 5px 7px;
  height: 200px;
  right: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-content: space-between;
  flex-direction: column;
  background-color: #fff;
}

.getlength0 {
  width: 18px;
  height: 30px;
  background: url(../assets/image/getnlength.png) center center no-repeat;
  background-size: 16px 16px;
}

.getarea0 {
  width: 18px;
  height: 30px;
  background: url(../assets/image/getarea.png) center center no-repeat;
  background-size: 16px 16px;
}
.el-icon-split{
  width: 16px;
  height: 16px;
  background: url(../assets/image/split.png) center center no-repeat !important;
  background-size: 16px 16px;
}

.el-icon-burrow{
  width: 16px;
  height: 16px;
  background: url(../assets/image/burrow.png) center center no-repeat !important;
  background-size: 16px 16px;
}

.el-icon-join{
  width: 16px;
  height: 16px;
  background: url(../assets/image/join.png) center center no-repeat !important;
  background-size: 16px 16px;
}

.el-icon-union{
  width: 16px;
  height: 16px;
  background: url(../assets/image/union.png) center center no-repeat !important;
  background-size: 16px 16px;
}

#vue-openlayers {
		width: 800px;
		height: 470px;
		margin: 0 auto;
		border: 1px solid #42B983;
		position: relative;
	}

	.ol-popup {
		position: absolute;
		background-color: rgba(255, 0, 0, 0.8);
		padding: 5px;
		border-radius: 5px;
		border: 1px solid #cccccc;
		bottom: 12px;
		left: -50px;
		color: #FFFFFF;
		min-width: 200px;
	}

	.ol-popup:after,
	.ol-popup:before {
		top: 100%;
		border: solid transparent;
		content: " ";
		height: 0;
		width: 0;
		position: absolute;
		pointer-events: none;
	}

	.ol-popup:after {
		border-top-color: rgba(255, 0, 0, 0.8);
		border-width: 10px;
		left: 48px;
		margin-left: -10px;
	}

	.ol-popup:before {
		border-top-color: #cccccc;
		border-width: 11px;
		left: 48px;
		margin-left: -11px;
	}

</style>
